/**
 * 
 */
package model;

import java.util.Iterator;

import fpt.com.Product;

public class Order extends java.util.ArrayList<Product> implements fpt.com.Order {

	private static final long serialVersionUID = 7816822261089546027L;

	// Bestellmenge und Summe der Preise
	private double sum;
	private int quantity;

	public Order() {

	}

	public boolean add(Product p) {
		boolean b = super.add(p);
		updateList();
		return b;
	}

	/*
	 * Überprüft am Namen, ob ein Produkt schon in der Order vorhanden ist.
	 * Wenn ja, dann wird die Quantity dieses Produktes entsprechend erhöht.
	 * Wenn nicht, dann wird es durch add() hinzugefügt
	 */
	public void addIncreaseQuantityIfProductAlrasyExists(Product productToAdd) {
		String name = productToAdd.getName();
		Boolean alreadyExists = false;
		Product alreadyExistingProduct = null;
		for (Product p : this) {
			if (name.equals(p.getName())) {
				alreadyExists = true;
				alreadyExistingProduct = p;
				break;
			}
		}
		if (alreadyExists) {
			alreadyExistingProduct.setQuantity(alreadyExistingProduct.getQuantity()
					+ productToAdd.getQuantity());
			updateList();
		} else {
			this.add(productToAdd);
		}
	}

	@Override
	public boolean delete(Product p) {
		boolean b = remove(p);
		// sum und quantity updaten
		updateList();
		return b;
	}

	private void updateList() {
		sum = 0;
		quantity = 0;
		for (Iterator<Product> i = iterator(); i.hasNext();) {
			Product p = i.next();
			sum += p.getPrice() * p.getQuantity();
			quantity += p.getQuantity();
		}
	}

	@Override
	public Product findProductById(long id) {

		for (Iterator<Product> i = iterator(); i.hasNext();) {
			Product p = i.next();
			long pId = p.getId();
			if (id == pId) {
				return p;
			}
		}
		return null;
	}

	@Override
	public Product findProductByName(String name) {

		for (Iterator<Product> i = iterator(); i.hasNext();) {
			Product p = i.next();
			String pName = p.getName();
			if (name.equals(pName)) {
				return p;
			}
		}
		return null;
	}

	@Override
	public double getSum() {
		return sum;
	}

	@Override
	public int getQuantity() {
		return quantity;
	}

	public void setSum(double sum) {
		this.sum = sum;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

}
